package com.zx.task.manager.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * description: 模版解析 <br>
 * create: 2025-10-23 00:58
 * </p>
 *
 * @author zhou  xun
 */
public class JsonTemplateUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");

    /**
     * 使用JSON字符串数据替换模板中的占位符
     */
    public static String processTemplateWithJsonData(String template, String jsonData) {
        try {
            // 解析数据JSON
            Map<String, String> dataMap = parseJsonToMap(jsonData);

            // 处理模板
            return processTemplate(template, dataMap);
        } catch (Exception e) {
            throw new RuntimeException("处理JSON模板失败", e);
        }
    }

    /**
     * 将JSON字符串解析为Map
     */
    private static Map<String, String> parseJsonToMap(String jsonData) throws Exception {
        Map<String, String> result = new HashMap<>();
        JsonNode rootNode = objectMapper.readTree(jsonData);

        Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            result.put(entry.getKey(), entry.getValue().asText());
        }

        return result;
    }

    /**
     * 使用Map数据替换模板中的占位符
     */
    private static String processTemplate(String template, Map<String, String> data) {
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String key = matcher.group(1);
            String replacement = data.getOrDefault(key, "");
            // 对特殊字符进行转义
            replacement = escapeJsonString(replacement);
            matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(result);

        return result.toString();
    }

    /**
     * 转义JSON字符串中的特殊字符
     */
    private static String escapeJsonString(String input) {
        if (input == null) return "";

        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}
